package com.leha.forum.lehare.controller;

import com.leha.forum.lehare.entity.Permission;
import com.leha.forum.lehare.entity.Role;
import com.leha.forum.lehare.response.Result;
import com.leha.forum.lehare.service.PermissionService;
import com.leha.forum.lehare.service.RolePermissionService;
import com.leha.forum.lehare.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * @author lovelycat
 * @version 1.0
 * @since 2025-04-17 14:04
 */
@RestController
@RequestMapping("/rbac")
public class RBACController {
    @Resource
    private RoleService roleService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RolePermissionService rolePermissionService;


    @GetMapping("/listAllRoles")
    public Result<?> listAllRoles() {
        return Result.success("", roleService.list());
    }

    @GetMapping("/listAllPermissions")
    public Result<?> listAllPermissions() {
        return Result.success("", permissionService.list());
    }

    @PostMapping("/saveRole")
    public Result<?> saveOrUpdateRole(@RequestBody Role role) {
        if (roleService.saveOrUpdateRole(role)) {
            return Result.success("保存成功", null);
        } else {
            return Result.failed(401, "保存失败");
        }
    }

    @PostMapping("/deleteRole")
    public Result<?> deleteRole(Integer roleId) {
        if (roleService.deleteRole(roleId)) {
            return Result.success("删除成功", null);
        } else {
            return Result.failed(401, "删除失败");
        }
    }

    @PostMapping("/deletePermission")
    public Result<?> deletePermission(Integer permissionId) {
        if (permissionService.deletePermission(permissionId)) {
            return Result.success("删除成功", null);
        } else {
            return Result.failed(401, "删除失败");
        }
    }

    @PostMapping("/savePermission")
    public Result<?> saveOrUpdatePermission(@RequestBody Permission permission) {
        if (permissionService.saveOrUpdatePermission(permission)) {
            return Result.success("保存成功", null);
        } else {
            return Result.failed(401, "保存失败");
        }
    }

    @GetMapping("/getRolePermissions")
    public Result<?> getRolePermissions(Integer roleId) {
        return Result.success("", rolePermissionService.getRolePermissions(roleId, permissionService));
    }

    @PostMapping("/bindRolePermissions")
    public Result<?> bindRolePermissions(Integer roleId, Integer permissionId) {
        return Result.success("", rolePermissionService.bindPermission(roleId, permissionId));
    }

    @PostMapping("/unbindRolePermissions")
    public Result<?> unbindRolePermissions(Integer roleId, Integer permissionId) {
        return Result.success("", rolePermissionService.unbindPermission(roleId, permissionId));
    }
}
